import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart'; // 需要添加 video_player 依赖
import '../models/post.dart';
import '../models/comment.dart'; // 导入 Comment 模型
import '../data/data_repository.dart';
import 'package:intl/intl.dart'; // 用于日期格式化

class VideoListPage extends StatefulWidget {
  const VideoListPage({Key? key}) : super(key: key);

  @override
  _VideoListPageState createState() => _VideoListPageState();
}

class _VideoListPageState extends State<VideoListPage> {
  final List<Post> _videoPosts = [];
  int _currentPage = 1;
  bool _isLoading = false;
  bool _hasMoreData = true;
  PageController _pageController = PageController();
  int _currentIndex = 0; // Track current page index

  // Store controllers for each video
  final Map<int, VideoPlayerController> _controllers = {};
  final Map<int, Future<void>> _initializeVideoPlayerFutures = {};

  @override
  void initState() {
    super.initState();
    _loadVideoPosts();
    _pageController.addListener(() {
      int nextPage = _pageController.page!.round();
      if (nextPage != _currentIndex) {
        // Pause previous video
        _controllers[_currentIndex]?.pause();
        setState(() {
          _currentIndex = nextPage;
        });
        // Play current video (if initialized)
        _playCurrentVideo();
        // Load more data if near the end
        if (nextPage == _videoPosts.length - 2 && !_isLoading && _hasMoreData) {
          _loadVideoPosts();
        }
      }
    });
  }

  Future<void> _loadVideoPosts() async {
    if (_isLoading || !_hasMoreData) return;

    setState(() => _isLoading = true);
    try {
      final newPosts = await DataRepository.fetchVideoPosts(page: _currentPage);
      if (!mounted) return; // Check if the widget is still mounted
      setState(() {
        if (newPosts.isEmpty) {
          _hasMoreData = false;
        } else {
          _videoPosts.addAll(newPosts);
          // Initialize controllers for new posts
          for (int i = _videoPosts.length - newPosts.length; i < _videoPosts.length; i++) {
             _initializeController(i);
          }
          _currentPage++;
        }
        _isLoading = false;
      });
       // Auto-play the first video if it's just loaded
      if (_currentPage == 2 && _videoPosts.isNotEmpty) { // _currentPage becomes 2 after first load
         _playCurrentVideo();
      }
    } catch (e) {
      if (!mounted) return;
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to load videos: $e')),
      );
    }
  }

  void _initializeController(int index) {
    final post = _videoPosts[index];
    if (post.videoUrl != null && _controllers[index] == null) {
      final controller = VideoPlayerController.networkUrl(Uri.parse(post.videoUrl!));
      _controllers[index] = controller;
      _initializeVideoPlayerFutures[index] = controller.initialize().then((_) {
         // Ensure the first frame is shown after the video is initialized
         if (mounted) {
           setState(() {});
           // If this is the current page, start playing
           if (index == _currentIndex) {
             _playCurrentVideo();
           }
         }
      }).catchError((error) {
         print("Error initializing video for index $index: $error");
         if(mounted) {
           setState(() {
             // Optionally handle the error state in the UI for this specific video
           });
         }
      });
      controller.setLooping(true); // Loop the video
    }
  }

  void _playCurrentVideo() {
     final controller = _controllers[_currentIndex];
     if (controller != null && controller.value.isInitialized && !controller.value.isPlaying) {
       controller.play();
       if (mounted) setState(() {}); // Update UI to reflect playing state if needed
     }
  }


  @override
  void dispose() {
    // 释放所有视频控制器
    for (var controller in _controllers.values) {
      controller.dispose();
    }
    _controllers.clear();
    _pageController.dispose();
    super.dispose();
  }

  // 加载视频控制器
  void _initializeControllerAtIndex(int index) {
    if (index >= _videoPosts.length || _controllers.containsKey(index)) return;
    
    final videoUrl = _videoPosts[index].videoUrl;
    if (videoUrl == null) return;
    
    final controller = VideoPlayerController.network(videoUrl);
    _controllers[index] = controller;
    _initializeVideoPlayerFutures[index] = controller.initialize().then((_) {
      if (index == _currentIndex) {
        controller.play();
        controller.setLooping(true);
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: const Text('视频', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.transparent, // 保持AppBar透明
        elevation: 0, // 移除阴影
        // 移除了leading属性，这样就不会显示返回按钮
      ),
      body: _buildVideoList(),
    );
  }

  Widget _buildVideoList() {
    if (_videoPosts.isEmpty && _isLoading) {
      return const Center(child: CircularProgressIndicator());
    } else if (_videoPosts.isEmpty && !_hasMoreData) {
      return const Center(child: Text("没有更多视频了", style: TextStyle(color: Colors.white)));
    }

    return PageView.builder(
      controller: _pageController,
      scrollDirection: Axis.vertical,
      itemCount: _videoPosts.length + (_isLoading ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == _videoPosts.length) {
          return const Center(child: CircularProgressIndicator());
        }
        final post = _videoPosts[index];
        final controller = _controllers[index];
        final initFuture = _initializeVideoPlayerFutures[index];

        return FutureBuilder(
          future: initFuture,
          builder: (context, snapshot) {
            // Stack allows overlaying elements
            return Stack(
              fit: StackFit.expand, // Make stack fill the page
              children: [
                // Video Player Background
                (controller != null && controller.value.isInitialized)
                    ? GestureDetector(
                        onTap: () {
                          // Toggle play/pause on tap
                          if (controller.value.isPlaying) {
                            controller.pause();
                          } else {
                            controller.play();
                          }
                          setState(() {}); // Update icon
                        },
                        child: FittedBox(
                          fit: BoxFit.cover, // Cover the screen
                          child: SizedBox(
                             width: controller.value.size.width,
                             height: controller.value.size.height,
                             child: VideoPlayer(controller),
                          ),
                        ),
                      )
                    : Container( // Placeholder while loading or if error
                        color: Colors.black,
                        child: Center(
                          child: snapshot.connectionState == ConnectionState.waiting
                              ? const CircularProgressIndicator()
                              : const Icon(Icons.error_outline, color: Colors.red, size: 48),
                        ),
                      ),

                // Play/Pause Button Overlay (optional, as tap toggles)
                if (controller != null && controller.value.isInitialized && !controller.value.isPlaying)
                  Center(
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white.withOpacity(0.7),
                      size: 80.0,
                    ),
                  ),

                // UI Overlay (Info and Actions)
                _buildVideoOverlay(post),
              ],
            );
          },
        );
      },
    );
  }

  // 修改 Overlay UI
  Widget _buildVideoOverlay(Post post) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.only(bottom: 16.0, left: 16.0, right: 16.0), // 调整 padding
        child: Row( // 改为 Row 布局
          crossAxisAlignment: CrossAxisAlignment.end, // 底部对齐
          children: [
            // 左侧信息区域
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end, // 内容也底部对齐
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // User Info Row
                  Row(
                    children: [
                      CircleAvatar(
                        backgroundImage: NetworkImage(post.userAvatarUrl),
                        radius: 20,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        post.userNickname,
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          shadows: <Shadow>[
                             Shadow(offset: Offset(1.0, 1.0), blurRadius: 3.0, color: Color.fromARGB(150, 0, 0, 0)),
                          ],
                        ),
                      ),
                      const SizedBox(width: 8),
                      // Follow Button
                      ActionChip(
                        label: Text(post.isFollowed ? '已关注' : '关注', style: TextStyle(color: post.isFollowed ? Colors.grey : Colors.white)),
                        backgroundColor: post.isFollowed ? Colors.white.withOpacity(0.3) : Colors.redAccent,
                        onPressed: () {
                          setState(() {
                            post.isFollowed = !post.isFollowed;
                          });
                        },
                        padding: EdgeInsets.zero, // 减少内边距
                        labelPadding: const EdgeInsets.symmetric(horizontal: 8), // 调整标签边距
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, // 减少点击区域
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  // Post Title/Content
                  Text(
                    post.title,
                    style: const TextStyle(
                       color: Colors.white,
                       shadows: <Shadow>[
                          Shadow(offset: Offset(1.0, 1.0), blurRadius: 3.0, color: Color.fromARGB(150, 0, 0, 0)),
                       ],
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 右侧操作按钮区域
            Padding(
              padding: const EdgeInsets.only(left: 16.0), // 与左侧内容间隔
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end, // 按钮列也底部对齐
                children: [
                  _buildActionButton(
                    Icons.favorite,
                    post.isLiked ? '已赞' : '点赞',
                    post.likesCount,
                    () {
                      setState(() {
                        post.isLiked = !post.isLiked;
                        post.likesCount += post.isLiked ? 1 : -1;
                      });
                    },
                  ),
                  const SizedBox(height: 16), // 按钮间距
                  _buildActionButton(
                    Icons.comment,
                    '评论',
                    post.commentsCount,
                    () {
                      // 点击评论按钮，显示评论列表 BottomSheet
                      _showCommentBottomSheet(context, post);
                    },
                  ),
                  // 可以添加分享等其他按钮
                  const SizedBox(height: 16),
                  // 例如分享按钮
                  // _buildActionButton(
                  //   icon: Icons.share,
                  //   count: 0, // 分享数
                  //   color: Colors.white,
                  //   onPressed: () { /* TODO: Implement share action */ },
                  // ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Helper widget for action buttons (Like, Comment, etc.)
  Widget _buildActionButton(IconData icon, String label, int count, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Icon(
            icon,
            color: Colors.white,
            size: 30,
            shadows: const <Shadow>[
              Shadow(offset: Offset(1.0, 1.0), blurRadius: 3.0, color: Color.fromARGB(150, 0, 0, 0)),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              shadows: <Shadow>[
                Shadow(offset: Offset(1.0, 1.0), blurRadius: 3.0, color: Color.fromARGB(150, 0, 0, 0)),
              ],
            ),
          ),
          const SizedBox(height: 2),
          Text(
            count.toString(),
            style: const TextStyle(
               color: Colors.white,
               fontSize: 12,
               shadows: <Shadow>[
                  Shadow(offset: Offset(1.0, 1.0), blurRadius: 3.0, color: Color.fromARGB(150, 0, 0, 0)),
               ],
            ),
          ),
        ],
      ),
    );
  }


  // 显示评论列表的 BottomSheet
  void _showCommentBottomSheet(BuildContext context, Post post) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许内容滚动且高度可变
      backgroundColor: const Color(0xFFFFF3EB), // 使用米白背景色
      shape: const RoundedRectangleBorder( // 圆角
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.0)),
      ),
      builder: (context) {
        // 使用 StatefulWidget 来管理评论输入和列表状态
        return CommentBottomSheet(post: post);
      },
    );
  }
} // End of _VideoListPageState

// --- 新增评论 BottomSheet Widget ---
class CommentBottomSheet extends StatefulWidget {
  final Post post;

  const CommentBottomSheet({Key? key, required this.post}) : super(key: key);

  @override
  _CommentBottomSheetState createState() => _CommentBottomSheetState();
}

class _CommentBottomSheetState extends State<CommentBottomSheet> {
  final TextEditingController _commentController = TextEditingController();
  late List<Comment> _comments; // 本地评论列表状态

  @override
  void initState() {
    super.initState();
    // 初始化本地评论列表
    _comments = List.from(widget.post.comments);
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  // 添加新评论的逻辑
  void _addComment() {
    final text = _commentController.text.trim();
    if (text.isNotEmpty) {
      // 创建一个新的模拟评论 (实际应用中应来自当前用户)
      final newComment = Comment(
        commentId: "new_${DateTime.now().millisecondsSinceEpoch}",
        userId: "currentUser", // 模拟当前用户ID
        userNickname: "我", // 模拟当前用户昵称
        userAvatarUrl: "https://via.placeholder.com/150/currentUser", // 模拟当前用户头像
        content: text,
        ctime: DateTime.now(),
      );

      setState(() {
        // 更新本地评论列表
        _comments.insert(0, newComment); // 在列表开头插入新评论
        widget.post.comments = _comments; // 更新原始 Post 对象的评论列表 (可选)
        widget.post.commentsCount = _comments.length; // 更新评论数
      });

      _commentController.clear(); // 清空输入框
      FocusScope.of(context).unfocus(); // 关闭键盘

      // TODO: 调用 API 将评论发送到后端
      print("New comment added: ${newComment.content}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).viewInsets.bottom,
      ),
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.75,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题栏
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '评论 (${_comments.length})',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333), // 使用文本主色
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close, color: Color(0xFF666666)), // 使用文本次要色
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
          ),
          const Divider(height: 1, color: Color(0xFFFFD7C5)), // 使用浅橙色作为分隔线
          // 评论列表
          Expanded(
            child: _comments.isEmpty
                ? const Center(child: Text('暂无评论，快来抢沙发吧！', style: TextStyle(color: Color(0xFF666666)))) // 使用文本次要色
                : ListView.builder(
                    itemCount: _comments.length,
                    itemBuilder: (context, index) {
                      final comment = _comments[index];
                      return ListTile(
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(comment.userAvatarUrl),
                          radius: 18,
                        ),
                        title: Text(comment.userNickname, style: const TextStyle(color: Color(0xFF333333), fontSize: 14, fontWeight: FontWeight.bold)), // 使用文本主色
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(comment.content, style: const TextStyle(color: Color(0xFF666666), fontSize: 14)), // 使用文本次要色
                            const SizedBox(height: 4),
                            Text(
                              DateFormat('MM-dd HH:mm').format(comment.ctime), // 格式化时间
                              style: const TextStyle(color: Color(0xFF999999), fontSize: 12), // 使用文本浅色
                            ),
                          ],
                        ),
                        dense: true,
                      );
                    },
                  ),
          ),
          const Divider(color: Color(0xFFFFD7C5)), // 使用浅橙色作为分隔线
          // 评论输入区域
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _commentController,
                    style: const TextStyle(color: Color(0xFF333333)), // 使用文本主色
                    decoration: InputDecoration(
                      hintText: '留下你的精彩评论吧...',
                      hintStyle: const TextStyle(color: Color(0xFF999999)), // 使用文本浅色
                      filled: true,
                      fillColor: const Color(0xFFFFD7C5), // 使用浅橙色作为输入框背景
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                        borderSide: BorderSide.none,
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
                    ),
                    textInputAction: TextInputAction.send, // 键盘显示发送按钮
                    onSubmitted: (_) => _addComment(), // 回车发送
                  ),
                ),
                const SizedBox(width: 8),
                IconButton(
                  icon: const Icon(Icons.send, color: Color(0xFFFF5A33)), // 使用主色
                  onPressed: _addComment, // 点击发送按钮
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}